/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务                                                   
*│　作    者：sys                                              
*│　创建时间：2020-12-02 14:55:26   
*│　说    明：代码生成器生成   
*└──────────────────────────────────────────────────────────────┘
*/
using SXFramWork.Core;
using SXFramWork.Model;
using SXFramWork.Repository;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SXFramWork.Service
{
    /// <summary>
	/// SysLog服务层
	/// </summary>
    public class SysLogService: ISysLogService
    {
        private readonly ISysLogRepository _repository;

        public SysLogService(ISysLogRepository repository)
        {
            _repository = repository;
        }

        public async Task<IApiResult> Query(LogQueryModel model)
        {
            var result = new PageResult<SysLogEntity>
            {
                Rows = await _repository.Query(model),
                TotalCount = model.TotalCount
            };
            return ApiResult.Ok(result);
        }

        public async Task<IApiResult> Delete(string ids)
        {
            var res= await _repository.DeleteManyAsync(ids.Split(',').ToList(), "syslog");
            if (res > 0)
                return ApiResult.Ok(res);
            else
                return ApiResult.NotOk("删除失败");
        }

        public async Task<IApiResult> GetErrorLog(string rootPath)
        {
            var path = Path.Combine(rootPath, "logs");
            DirectoryInfo dir_info = new DirectoryInfo(path);
            if (!dir_info.Exists)
                dir_info.Create();
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            var filelist = dir_info.GetFiles();
            var task = Task.Run(() =>
            {
                for (int i = 0; i < filelist.Length; i++)
                {
                    Dictionary<string, string> data = new Dictionary<string, string>();
                    data["Name"]= filelist[i].Name;
                    using (StreamReader sr = filelist[i].OpenText())
                    {
                        data["Content"] = sr.ReadToEnd();
                        sr.Dispose();
                        sr.Close();
                    }
                    list.Add(data);
                }
                return list;
            });
            await task;
            return ApiResult.Ok(list);
        }

    }
}